using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Identity.Contexts;
using Identity.Data;
using Identity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
 

namespace Identity.Extensions;

public static class IdentityDatabaseInitializer
{
    public static async Task InitializeDatabaseAsync(IServiceProvider serviceProvider, IConfiguration configuration)
    {
        using var scope = serviceProvider.CreateScope();
        var services = scope.ServiceProvider;
        try
        {
            var Factory = services.GetRequiredService<IDbContextFactory<SysContext>>();
            var _User = services.GetRequiredService<UserManager<User>>();
            var dbContext = await Factory.CreateDbContextAsync();

            // 检查数据库是否存在
            if (!dbContext.Database.CanConnect())
            {
                Console.WriteLine("数据库不存在，正在创建数据库...");
                await dbContext.Database.EnsureCreatedAsync();
                Console.WriteLine("数据库创建成功！");


                if (!dbContext.Users.Any() && !dbContext.UserRoles.Any() && !dbContext.Roles.Any() && !dbContext.Navigationlists.Any())
                {
                    var jsonFilePath = configuration?["DataInitialization:JsonFilePath"] ?? "Identity.json";
                    if (File.Exists(jsonFilePath))
                    {
                        var jsonData = await File.ReadAllTextAsync(jsonFilePath);
                        var data = JsonSerializer.Deserialize<DatabaseInitializationData>(jsonData);
                        // await using var transaction = await dbContext.Database.BeginTransactionAsync();
                        if (data.Roles?.Count > 0)
                        {
                            await dbContext.Roles.AddRangeAsync(data.Roles);
                            await dbContext.SaveChangesAsync();
                        }

                        if (data.Users?.Count > 0)
                        {
                            // await dbContext.Users.AddRangeAsync(data.Users);
                            // await dbContext.SaveChangesAsync();
                            foreach (var user in data.Users)
                            {

                                await _User.CreateAsync(user, "123456");
                                // Console.WriteLine(x.Succeeded);
                                // _User.Dispose();
                            }
                        }

                        if (data.UserRoles?.Count > 0)
                        {
                            await dbContext.UserRoles.AddRangeAsync(data.UserRoles);
                            await dbContext.SaveChangesAsync();
                        }

                        if (data.Navigations?.Count > 0)
                        {
                            await dbContext.Navigationlists.AddRangeAsync(data.Navigations);
                            await dbContext.SaveChangesAsync();
                        }

                        if (data.NavigationRoles?.Count > 0)
                        {
                            await dbContext.Navigationroles.AddRangeAsync(data.NavigationRoles);
                            await dbContext.SaveChangesAsync();
                        }
                        // await transaction.CommitAsync();


                    }
                }

                Console.WriteLine("初始数据已插入！");


            }
            else
            {
                Console.WriteLine("数据库已存在，跳过创建。");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }
}